package org.zasadnyy.redlions.players.server.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import org.zasadnyy.redlions.players.server.dao.Dao;
import org.zasadnyy.redlions.players.server.model.TournamentObject;
import org.zasadnyy.redlions.players.server.persistance.PmfFactory;

import com.google.appengine.api.datastore.Key;

public class JdoTournmaentDao implements Dao<TournamentObject> {

	private PersistenceManagerFactory pmfInstance = PmfFactory.get();

	@Override
	public TournamentObject getById(Key id) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			return pm.getObjectById(TournamentObject.class, id);
		} finally {
			pm.close();
		}
	}

	@Override
	public List<TournamentObject> getAll() {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			List<TournamentObject> tournaments = new ArrayList<TournamentObject>();
			Extent<TournamentObject> extent = pm.getExtent(TournamentObject.class,
					false);
			for (TournamentObject tournament : extent) {
				tournaments.add(tournament);
			}
			extent.closeAll();

			return tournaments;
		} finally {
			pm.close();
		}
	}

	@Override
	public Key addOrEdit(TournamentObject tournament) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.makePersistent(tournament);
			pm.refresh(tournament);
		} finally {
			pm.close();
		}
		return tournament.getId();
	}

	@Override
	public void deleteById(Key id) {
		PersistenceManager pm = pmfInstance.getPersistenceManager();
		try {
			pm.deletePersistent(pm.getObjectById(TournamentObject.class, id));
		} finally {
			pm.close();
		}
	}

}
